package com.kokomi.listener;

import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.mail.SimpleMailMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.stereotype.Component;

import java.util.Map;

@Component
@Slf4j
public class EmailListener {

    @Autowired
    private JavaMailSender javaMailSender;

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 监听邮件队列，发送邮件
     * 对指定的队列进行监听，并且将数据注入给方法的形参
     */
    @RabbitListener(queues = "email.queue")
    public void sendEmail(Map<String, String> emailData) {

        log.info("接收到邮件发送请求，开始发送邮件");

        // 获取邮件数据
        String from = emailData.get("from");
        String to = emailData.get("to");
        String subject = emailData.get("subject");
        String context = emailData.get("context");

        // 发送邮件
        SimpleMailMessage mailMessage = new SimpleMailMessage();
        mailMessage.setFrom(from);
        mailMessage.setTo(to);
        mailMessage.setSubject(subject);
        mailMessage.setText(context);

        // 发送邮件
        javaMailSender.send(mailMessage);
    }
}
